Skip to content

fix: return 404 on undefined value - #1034

Merged
DilwoarH merged 4 commits into
mainfrom
rosado/fix-site-ref-error
Jun 28, 2025
Merged

fix: return 404 on undefined value#1034
DilwoarH merged 4 commits into
mainfrom
rosado/fix-site-ref-error

Conversation

@rosado

@rosado rosado commented Apr 23, 2025

Copy link
Copy Markdown
Contributor

What type of PR is this? (check all applicable)

  • Bug Fix

Description

An udefined value causes a 500, we should return a 404 instead.

Related Tickets & Documents

QA Instructions, Screenshots, Recordings

Going to this URL should return a 404, and not a 500

Added/updated tests?

  • Yes

QA sign off

  • Code has been checked and approved
  • Design has been checked and approved
  • Product and business logic has been checked and proved

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling to return a 404 error when no issue entities are available for an entity.
  • Tests
    • Enhanced test isolation and added a new test to verify correct behaviour when no issue entities are present.

@coderabbitai

coderabbitai Bot commented Apr 23, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

A guard clause was introduced at the beginning of the prepareEntity middleware to immediately return a 404 error when issueEntities is missing or empty. The rest of the middleware logic remains unchanged. Corresponding unit tests were refactored for better isolation and a new test was added to verify the new guard clause behaviour, ensuring that a MiddlewareError is thrown when no issue entities are present.

Changes

File(s) Change Summary
src/middleware/entityIssueDetails.middleware.js Added a guard clause in prepareEntity to throw a 404 error if issueEntities is missing or empty.
test/unit/middleware/entityIssueDetails.middleware.test.js Refactored test setup for isolation and added a test for the new guard clause handling empty issueEntities.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware (prepareEntity)
    participant Next

    Client->>Middleware (prepareEntity): Request with issueEntities
    alt issueEntities missing or empty
        Middleware (prepareEntity)->>Next: next(MiddlewareError("No issues for entity", 404))
    else issueEntities present
        Middleware (prepareEntity)->>Middleware (prepareEntity): Continue with normal processing
        Middleware (prepareEntity)->>Next: next()
    end
Loading

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • DilwoarH

Poem

A hop, a skip, a bounding leap,
Now errors for empty issues won’t creep.
With tests refactored, all neat and tight,
The middleware guards with all its might.
If issues are missing, a 404 you’ll see—
That’s one happy rabbit, coding with glee! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab6f2cf and b58bdea.

📒 Files selected for processing (2)
  • src/middleware/entityIssueDetails.middleware.js (1 hunks)
  • test/unit/middleware/entityIssueDetails.middleware.test.js (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/middleware/entityIssueDetails.middleware.js
  • test/unit/middleware/entityIssueDetails.middleware.test.js

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions

github-actions Bot commented Apr 23, 2025

Copy link
Copy Markdown

Coverage Report

Status Category Percentage Covered / Total
🔵 Lines 66.48% 5944 / 8940
🔵 Statements 66.48% 5944 / 8940
🔵 Functions 65.37% 253 / 387
🔵 Branches 79.7% 758 / 951
File Coverage
File Stmts Branches Functions Lines Uncovered Lines
Changed Files
src/middleware/entityIssueDetails.middleware.js 100% 76% 100% 100%
Generated in workflow #1085 for commit 0b91790 by the Vitest Coverage Report Action

@rosado
rosado requested a review from DilwoarH April 23, 2025 11:00
@rosado
rosado marked this pull request as ready for review April 23, 2025 11:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/middleware/entityIssueDetails.middleware.js (1)

91-93: Good addition of a guard clause to prevent 500 errors.

This guard clause effectively prevents accessing an undefined array element when issueEntities is empty or missing, directly addressing the bug causing the 500 error. Returning a 404 with a clear error message is appropriate for this case.

However, the condition could be slightly simplified:

-  if (!issueEntities || (issueEntities && issueEntities.length === 0)) {
+  if (!issueEntities || issueEntities.length === 0) {
    return next(new MiddlewareError('No issues for entity', 404))
  }

This works because if issueEntities is falsy, the right side won't evaluate due to short-circuit evaluation.

test/unit/middleware/entityIssueDetails.middleware.test.js (1)

47-67: Test name and implementation mismatch.

The test names in lines 47 and 58 mention checking req.issues, but the implementation in setRecordCount (line 70 in the middleware file) actually checks req.issueEntities. This could lead to confusion.

-  it('sets the record count to 0 if req.issues is undefined', () => {
+  it('sets the record count to 0 if req.issueEntities is undefined', () => {

And similarly:

-  it('sets the record count to 0 if req.issues is null', () => {
-    const req = { issues: null }
+  it('sets the record count to 0 if req.issueEntities is null', () => {
+    const req = { issueEntities: null }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8a416f and ab6f2cf.

📒 Files selected for processing (2)
  • src/middleware/entityIssueDetails.middleware.js (1 hunks)
  • test/unit/middleware/entityIssueDetails.middleware.test.js (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
test/unit/middleware/entityIssueDetails.middleware.test.js (1)
Learnt from: rosado
PR: digital-land/submit#657
File: test/unit/middleware/issueDetails.middleware.test.js:43-43
Timestamp: 2024-11-14T16:38:49.883Z
Learning: In `test/unit/middleware/issueDetails.middleware.test.js`, template params are verified with a schema, so it's acceptable for the test expectations to use primitive values while the test input uses an object for `issueEntitiesCount`.
🧬 Code Graph Analysis (1)
test/unit/middleware/entityIssueDetails.middleware.test.js (2)
src/middleware/entityIssueDetails.middleware.js (3)
  • req (88-88)
  • req (155-155)
  • prepareEntity (87-144)
src/utils/errors.js (1)
  • MiddlewareError (17-34)
🔇 Additional comments (3)
src/middleware/entityIssueDetails.middleware.js (1)

87-144:

Details

❓ Verification inconclusive

Consider relationship between prepareEntity's new guard clause and show404ifNoIssues middleware.

Both prepareEntity and show404ifNoIssues now handle the case of missing issues, but in slightly different ways and at different points in the middleware chain. This is likely intentional to provide different error messages based on context, but it's worth ensuring that having both checks is the desired behavior.

Looking at the middleware chain order in lines 174-195, show404ifNoIssues runs before prepareEntity, suggesting the new guard clause might never be reached in normal operation. Could you verify this is the intended behavior?


🏁 Script executed:

#!/bin/bash
# Check the relative position of both middlewares in the chain
echo "Middleware chain position:"
grep -n "show404ifNoIssues\|prepareEntity" src/middleware/entityIssueDetails.middleware.js

Length of output: 312


🏁 Script executed:

#!/bin/bash
# Display the implementation of show404ifNoIssues for comparison
rg -n "export const show404ifNoIssues" -A10 src/middleware/entityIssueDetails.middleware.js

Length of output: 373


Review redundancy between show404ifNoIssues and prepareEntity

The show404ifNoIssues middleware (lines 154–162) already returns a 404 when recordCount === 0 before prepareEntity ever runs (line 191). Meanwhile, prepareEntity has its own guard (lines 87–91) that checks for missing or empty issueEntities, which corresponds to the same condition and will never be reached in normal operation.

Please confirm whether this duplicate check is intentional or whether the guard in prepareEntity should be removed or changed (for example, to handle out‑of‑range pageNumber cases instead).

• src/middleware/entityIssueDetails.middleware.js
– prepareEntity guard at lines 87–91
– show404ifNoIssues implementation at lines 154–162

test/unit/middleware/entityIssueDetails.middleware.test.js (2)

71-89: Good refactoring using template objects and deep cloning.

Using template objects (reqTemplate and resTemplate) with structuredClone in the beforeEach hook is a good practice that ensures proper test isolation. This prevents test cases from mutating shared objects and affecting each other's results.


162-169: Well-written test for the new guard clause.

This test properly verifies the new guard clause behaviour, ensuring that when issueEntities is empty:

  1. req.entry remains undefined
  2. next is called with a MiddlewareError with the correct message and status code

This test case effectively covers the bug fix described in the PR objectives.

@rosado rosado changed the title Rosado/fix site ref error fix: return 404 on undefined value Apr 23, 2025
@DilwoarH
DilwoarH merged commit d5d8570 into main Jun 28, 2025
5 checks passed
@DilwoarH
DilwoarH deleted the rosado/fix-site-ref-error branch June 28, 2025 17:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants